package com.myedusys.service;

import Result.Result;
import com.myedusys.constant.UserConstant;
import com.myedusys.context.BaseContext;
import com.myedusys.exception.UpdatePwdException;
import com.myedusys.exception.UserLoginException;
import com.myedusys.mapper.UserMapper;
import com.myedusys.utils.JwtUtil;
import dto.UpdatePwdDto;
import entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.myedusys.properties.JwtProperties;
import vo.UserLoginVo;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {


    @Autowired
    UserMapper userMapper;

    @Resource
    JwtProperties jwtProperties;

    /**
     * 根据用户名找用户
     * @param username
     * @return
     */
    public User findByUserName(String username) {

        return userMapper.findByUserName(username);

    }

    /**
     * 注册用户
     * @param username
     * @param password
     */
    public void register(String username, String password) {
        //给密码进行md5加密
        password = Base64.getEncoder().encodeToString(password.getBytes());
        //进行添加
        userMapper.save(username,password);
    }

    /**
     * 对传过来的密码进行校验
     * @param username
     * @param password
     * @return
     */
    public UserLoginVo login(String username, String password) {
        //查询数据库是否存在该用户
        User user = userMapper.findByUserName(username);

        if (user==null) {
            throw new UserLoginException(UserConstant.USERNAME_ERROR);
        }

        //如果查到就把用户的密码和传过来的密码进行比对
        if (!user.getPassword().equals(Base64.getEncoder().encodeToString(password.getBytes()))) {
            throw new UserLoginException(UserConstant.USER_PASSWORD_ERROR);
        }

        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id",user.getId());
        cliams.put("username",user.getUsername());

        //登录成功
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                cliams);

        UserLoginVo userLoginVo = new UserLoginVo();

        BeanUtils.copyProperties(user,userLoginVo);

        userLoginVo.setToken(token);


        return userLoginVo;


    }

    public User findById(Long id) {
        return userMapper.findById(id);
    }

    /**
     * 更新用户信息
     * @param user
     */
    public void update(User user) {
        userMapper.update(user);
    }

    /**
     * 更新用户头像
     * @param avatarUrl
     */
    public void updateAvatar(String avatarUrl) {
        Long id = BaseContext.getCurrentId();
        userMapper.updateAvatar(avatarUrl,id);
    }

    /**
     * 更新密码
     * @param updatePwdDto
     */
    public void updatePwd(UpdatePwdDto updatePwdDto) {
        //校验参数
        String oldPwd = updatePwdDto.getOld_pwd();
        String newPwd = updatePwdDto.getNew_pwd();
        String rePwd = updatePwdDto.getRe_pwd();

        Long id = BaseContext.getCurrentId();
        User mapperById = userMapper.findById(id);

        //参数为空
        if (oldPwd.isBlank()||newPwd.isBlank()||rePwd.isBlank()) {
            throw new UpdatePwdException(UserConstant.USER_UPDATE_PWD_ERROR);
        }

        //旧密码与原密码不一致
        if (!Base64.getEncoder().encodeToString(oldPwd.getBytes()).equals(mapperById.getPassword())) {
            log.info("输入密码加密后为：{}",Base64.getEncoder().encodeToString(oldPwd.getBytes()));
            throw new UpdatePwdException(UserConstant.USER_UPDATE_PWD_ERROR_OLD_WITH_DATABASE);
        }

        //新密码和旧密码相同
        if (oldPwd.equals(newPwd)) {
            throw new UpdatePwdException(UserConstant.USER_UPDATE_PWD_SAME);
        }

        //新密码与重复密码不一致
        if (!newPwd.equals(rePwd)) {
            throw new UpdatePwdException(UserConstant.USER_UPDATE_PWD_NOT_SAME);
        }

        User user = User.builder()
                .id(id)
                .password(Base64.getEncoder().encodeToString(newPwd.getBytes()))
                .build();


        //完成密码更新
        userMapper.update(user);


    }
}
